package com.farm.configer.form;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.farm.configer.domain.ex.ConfigerMetaPara;
import com.farm.configer.form.impl.NoneConfigerModelImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;

public class FormModelUtils {

	/**
	 * 格式化json
	 * 
	 * @param configParas
	 * @return
	 * @throws IOException
	 */
	public static String formatObjTojson(Map<String, Object> configParas) throws IOException {
		ObjectMapper mapper = new ObjectMapper();
		String jsonString = mapper.writeValueAsString(configParas);
		mapper.enableDefaultTyping();
		String formattedJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(mapper.readTree(jsonString));
		return formattedJson;
	}

	public static String formatObjTojson(Object configParas) throws IOException {
		ObjectMapper mapper = new ObjectMapper();
		String jsonString = mapper.writeValueAsString(configParas);
		mapper.enableDefaultTyping();
		String formattedJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(mapper.readTree(jsonString));
		return formattedJson;
	}

	public static List<ConfigerMetaPara> formatParas(String configerid, String paras) throws IOException {
		List<Map<String, String>> paraList = convertJsonToListOfMaps(paras);
		List<ConfigerMetaPara> metaConfigs = new ArrayList<ConfigerMetaPara>();
		for (Map<String, String> node : paraList) {
			ConfigerMetaPara cm = new ConfigerMetaPara();
			cm.setCode(node.get("name"));
			cm.setJsonString(node.get("val"));
			metaConfigs.add(cm);
		}
		return metaConfigs;
	}

	public static List<Map<String, String>> convertJsonToListOfMaps(String jsonString) throws IOException {
		ObjectMapper mapper = new ObjectMapper();
		if (jsonString == null || jsonString.isEmpty()) {
			return Collections.emptyList();
		}
		return mapper.readValue(jsonString, mapper.getTypeFactory().constructCollectionType(List.class, Map.class));
	}

	public static Map<String, Object> jsonStrToObjects(String json) {
		ObjectMapper mapper = new ObjectMapper();
		try {
			// 将 JSON 字符串转换为 Map<String, Object>
			Map<String, Object> map = mapper.readValue(json,
					TypeFactory.defaultInstance().constructMapType(Map.class, String.class, Object.class));
			return map;
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException(e);

		}
	}
}
